package lab03.test01;

import java.io.*;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        /**
         * 读文件并输出内容
         *文件名由命令行给出且为绝对路径名
         */
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入需要读取的文件路径：\n例如：D:\\dev\\lab03\\Hello.txt");
        String path = sc.nextLine();

//        String path = "D:\\dev\\lab03\\Hello.txt";


        /*字符流*/
        BufferedWriter writer = null;
        BufferedReader reader = null;
        try {
            writer = new BufferedWriter(new FileWriter(path));
            reader = new BufferedReader(new FileReader(path));

            writer.write("Hello,字符流！！");
            writer.newLine();//换行
            writer.close();
            System.out.println("字符流写入完成！");



            //1.字符流来读
            //1.1一次读一行.readLine(),
            //1.2一次读一个字符.read()->返回ASCCII码整数
            System.out.println("字符流读一行："+reader.readLine());//返回String 读完之后返回null

            System.out.println("字符流读一个字符："+reader.read());//返回int 可使用char强制转换，读完返回-1



            reader.close();
        } catch (IOException e) {

            e.printStackTrace();
        }finally {
            //关闭文件
            try {
                writer.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

/***************************************分割线***************************************/

        /*字节流*/

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);

            //一次一个字节
            fileOutputStream.write(65);

            //一次多个字节
            byte[] b = new byte[2];
            b[0] = 65;
            b[1] = 66;
            fileOutputStream.write(b);

            //一次多个字节
            /*将一个String对象转换为字节码，返回byte[]*/
            fileOutputStream.write(new String("Hello!").getBytes());



        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
